<?php

error_reporting(E_ALL ^ E_WARNING);

require_once 'config/config.php';
require_once 'class/Core.php';

$core = new Core;
if (isset($config)) {
    $check = $core->init($config);
} else {
    echo "Please make sure that config.php is included.";
    die();
}

/**
 * Validate IP, Port or Host
 *
 * @param $address
 *
 * @return bool
 */
function isValidIpPort($address): bool
{
    if ((filter_var($address, FILTER_VALIDATE_IP) || filter_var($address, FILTER_VALIDATE_URL) || $address === 'localhost')) {
        return true;
    } elseif (preg_match('~\b([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}):([0-9]{1,10}\b)~', $address, $matches)) {
        if (! preg_match('/^([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$/m', $matches[2], $arraystr)) {
            return false;
        }

        return true;
    }

    return false;
}

$target    = '../installation/';
$canRemove = [];

if (is_dir($target)) {
    $files = glob('*', GLOB_MARK);

    foreach ($files as $file) {
        if (! is_writeable($file)) {
            $canRemove[] = $file;
        }
        if (is_dir($file)) {
            $files = glob($file . '*', GLOB_MARK);
            foreach ($files as $file) {
                if (! is_writeable($file)) {
                    $canRemove[] = $file;
                }
            }
        }
    }
}

if (isset($_POST['dbc'])) {
    $data   = json_decode($_POST['dbc'], true);
    $status = [];
    $cred   = [
        'CMS'   => ['host' => $data[0]['value'], 'user' => $data[2]['value'], 'pass' => $data[3]['value'], 'db' => $data[1]['value']],
        'AUTH'  => ['host' => $data[4]['value'], 'user' => $data[6]['value'], 'pass' => $data[7]['value'], 'db' => $data[5]['value']],
        'WORLD' => ['host' => $data[8]['value'], 'user' => $data[10]['value'], 'pass' => $data[11]['value'], 'db' => $data[9]['value']]
    ];

    $mysqli = new mysqli();
    $mysqli->set_opt(MYSQLI_OPT_READ_TIMEOUT, 3);

    foreach ($cred as $key => $check) {
        if (isValidIpPort($check['host']) && ! empty($check['user']) && ! empty($check['pass']) && ! empty($check['db'])) {
            $mysqli->connect($check['host'], $check['user'], $check['pass'], $check['db']);
            if (! $mysqli->connect_error) {
                $status[$key] = true;
            } else {
                $status[$key] = false;
            }
            $mysqli->close();
        } else {
            $status[$key] = false;
        }
    }

    echo json_encode($status);
    exit;
}

if ($_POST) {
    $core->setInput($_POST);

    if ($core->reWrite()) {
        $core->removeFiles($target);
    }
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>YesilCMS Installation (1/2)</title>
    <script src="../assets/core/js/jquery.min.js"></script>
    <script src="../assets/core/fontawesome/js/solid.min.js"></script>
    <script src="../assets/core/fontawesome/js/fontawesome.min.js"></script>
    <link rel="stylesheet" href="../assets/core/uikit/css/uikit.min.css"/>
    <script src="../assets/core/uikit/js/uikit.min.js"></script>
    <script src="../assets/core/uikit/js/uikit-icons.min.js"></script>
</head>
<style>
  html,
  p,
  a,
  .uk-alert,
  .uk-logo {
    background: transparent;
    color: #f3f3f3;
  }

  .uk-icon-button {
    color: #000;
  }

  body {
    background-color: #211510;
    background-image: url();
    background-position: top;
    background-size: 150%;
    background-repeat: repeat;
  }

  h1,
  h2,
  .uk-h1,
  .uk-h5,
  .uk-logo:hover {
    color: #f8b700 !important;
  }

  .uk-alert-success {
    background: #32d296 !important;
  }

  .uk-alert-warning {
    background: #c18f02 !important;
  }

  .uk-alert-danger {
    background: #f0506e !important;
  }

  .notify {
    -webkit-animation: flash linear 1s 3;
    -moz-animation: flash linear 1s 3;
    animation: flash linear 1s 3;
  }

  @-webkit-keyframes flash {
    0% {
      opacity: 1;
    }
    50% {
      opacity: 0.1;
    }
    100% {
      opacity: 1;
    }
  }

  @keyframes flash {
    0% {
      opacity: 1;
    }
    50% {
      opacity: 0.1;
    }
    100% {
      opacity: 1;
    }
  }

  .yesil-db-check {
    background-color: #ff5722;
    color: #fff;
    border: 1px solid transparent;
  }

  .yesil-db-check:hover {
    background-color: #d93806;
    color: #fff;
  }

  .success {
    color: #32d296;
  }

  .fail {
    color: #f0506e;
  }

  .modal {
    display: none;
    position: fixed;
    z-index: 1000;
    top: 0;
    left: 0;
    height: 100%;
    width: 100%;
    background: rgba(0, 0, 0, 0.75) url() 50% 50% no-repeat;
  }

  body.loading .modal {
    overflow: hidden;
  }

  body.loading .modal {
    display: block;
  }

</style>
<body>
<header>
    <div class="uk-navbar-container uk-navbar-transparent">
        <div class="uk-container">
            <nav class="uk-navbar" uk-navbar>
                <div class="uk-navbar-left">
                    <img width="48px"
                         src=''/>
                </div>
                <div class="uk-navbar-right">
                    <div class="uk-navbar-item">
                        <a target="_blank" href="https://github.com/yesilmen-vm/YesilCMS" class="uk-icon-button github uk-margin-small-right" uk-icon="icon: github; ratio:1.65"></a>
                    </div>
                </div>
            </nav>
        </div>
    </div>
</header>
<section class="uk-section uk-section-xsmall">
    <div class="uk-container">
        <div class="uk-grid uk-grid-small" data-uk-grid>
            <div class="uk-width-1-4@s"></div>
            <div class="uk-width-2-4@s">
                <h1 class="uk-h1 uk-text-bold uk-text-center uk-margin-remove">Installation (1/2)</h1>
                <p class="uk-text-small uk-text-center uk-margin-remove-top uk-margin-bottom">Please fill the form with your corresponding information to proceed with the installation.
                    <br/> For security measures, please create a separate user and password for each database. Define only the permissions that the created users need.</p>
                <?php if ($core->PHPVersion()): ?>
                    <div class="uk-alert-success" uk-alert>
                        <p><i class="fas fa-check-circle"></i> PHP Version <span class="uk-text-bold">(<?= PHP_VERSION; ?>)</span> is compatible.</p>
                    </div>
                <?php else: ?>
                    <div class="uk-alert-danger" uk-alert>
                        <p><i class="fas fa-times-circle"></i> PHP Version <span class="uk-text-bold">(<?= PHP_VERSION; ?>)</span> is not compatible, please use a version higher than 7.1. Recommended version is 7.4.x.</p>
                    </div>
                <?php endif; ?>
                <?php if (empty($canRemove)): ?>
                    <div class="uk-alert-success" uk-alert>
                        <p><i class="fas fa-check-circle"></i> The <span class="uk-text-bold">"Installation"</span> folder has the necessary permissions to be deleted automatically after installation.</p>
                    </div>
                <?php else: ?>
                    <div class="uk-alert-danger" uk-alert>
                        <p><i class="fas fa-times-circle"></i> You do not have the necessary permissions to delete the following files in <span class="uk-text-bold">Installation</span> folder:<br/><br/>
                            <?php foreach ($canRemove as $path): ?>
                                <?= "<strong>Installation/</strong>" . $path . '<br>' ?>
                            <?php endforeach; ?><br/>Please refresh the page by editing the file permissions or manually delete the "Installation" file after installation.</p>
                    </div>
                <?php endif; ?>
                <?php if ($core->getError()): ?>
                    <?php echo "<div class='uk-alert-danger' uk-alert><h5 class='uk-text-uppercase uk-text-bold uk-margin-remove'><i class='fas fa-exclamation-circle'></i> Error</h5><ul class='uk-margin-remove'>"; ?>
                    <?php foreach ($core->getError() as $item): ?>
                        <?php echo "<li>$item</li>"; ?>
                    <?php endforeach; ?>
                    <?php echo "</ul></div>"; ?>
                <?php endif; ?>
                <?php foreach ($core->getExtensionState() as $ext => $enabled) :
                    $allGood = true; ?>
                    <?php if (! $enabled) :
                    $allGood = false; ?>
                    <div class="uk-alert-danger" uk-alert>
                        <p><i class="fas fa-times-circle"></i> The php <strong><?= $ext ?></strong> extension is required.</p>
                    </div>
                <?php endif; ?>
                <?php endforeach; ?>
                <?php if ($allGood) : ?>
                    <div class="uk-alert-success" uk-alert>
                        <p><i class="fas fa-check-circle"></i> Required <strong>PHP Extensions</strong> are installed and active.</p>
                    </div>
                <?php endif; ?>
                <?php if ($_SERVER['REMOTE_ADDR'] == '127.0.0.1') :
                    $possibleFolder = ltrim(preg_replace('#/[^/]*$#i', '', (preg_replace('#/[^/]*$#i', '', $_SERVER['PHP_SELF']))), '/'); ?>
                    <div class="uk-alert-warning" uk-alert>
                        <p><i class="fas fa-exclamation-circle"></i> It seems that you are running this CMS under <strong>Localhost.</strong> If the CMS is not in the <strong>web root</strong> folder,
                            please add the existing folder name (possibly: <strong><?= $possibleFolder; ?></strong>) to the <code>$config['base_url']</code> definition in <code>application/config/config.php</code> for a seamless installation and usage.<br/>
                            <br/>Example: Update <code>$config['base_url']</code> from <code>$protocol . $_SERVER['HTTP_HOST'] . '/';</code> to <code>$protocol . $_SERVER['HTTP_HOST'] . '/<?= !empty($possibleFolder) && strlen($possibleFolder) > 0 ? $possibleFolder : 'myFolder'; ?>/';</code><br/>
                            <br/>Otherwise, you can safely ignore this message and continue with installation.</p>
                    </div>
                <?php endif; ?>
                <form id="form_install" action="" method="POST" accept-charset="utf-8" autocomplete="off">
                    <h2 class="uk-h5 uk-heading-line uk-margin-small uk-text-uppercase uk-text-bold"><span><i class="fas fa-cog fa-spin"></i> General Settings</span></h2>
                    <div class="uk-margin-small uk-light">
                        <label class="uk-form-label">CMS Main Language:</label>
                        <div class="uk-form-controls uk-margin-small-bottom">
                            <select name="language" class="uk-select" id="language">
                                <option value="english">English</option>
                                <option value="spanish">Spanish</option>
                                <option value="german">German</option>
                            </select>
                        </div>
                        <label class="uk-form-label">CMS Theme:</label>
                        <div class="uk-form-controls">
                            <select name="theme" class="uk-select" id="theme">
                                <option value="yesilcms">YesilCMS by Yesilmen (recommended)</span></option>
                                <option value="default">Default by BlizzCMS</option>
                            </select>
                        </div>
                        <label class="uk-form-label">CMS Secure Cookie:<br><small>Keep it disabled for HTTP connections, if you are running site through HTTPs it is recommended to enable this.</small></label>
                        <div class="uk-form-controls">
                            <select name="cookie_secure" class="uk-select" id="cookie_secure">
                                <option value="false">Disabled (HTTP)</span></option>
                                <option value="true" <?= empty($_SERVER['HTTPS']) ?: 'selected' ?>>Enabled (HTTPs)</option>
                            </select>
                        </div>
                    </div>
                    <h2 class="uk-h5 uk-heading-divider uk-margin-top uk-margin-small-bottom uk-text-uppercase uk-text-bold"><span><i class="fas fa-house-user"></i> CMS Database</span>
                        <span class="uk-align-right uk-margin-remove" id="s_cms"></span>
                    </h2>
                    <p class="uk-margin-remove-top">This database contains the general structure (such as modules, migrations etc.) for the CMS.</p>
                    <div class="uk-margin-small uk-light">
                        <div class="uk-grid uk-grid-small" data-uk-grid>
                            <div class="uk-inline uk-width-1-2@s">
                                <label class="uk-form-label"><strong>CMS</strong> Database Hostname: <small>(also :port if exists)</small></label>
                                <div class="uk-form-controls">
                                    <input name="cms_host" class="uk-input" type="text" id="cms_host" placeholder="Hostname (eg. 127.0.0.1 or 127.0.0.1:3307)" required>
                                </div>
                            </div>
                            <div class="uk-inline uk-width-1-2@s">
                                <label class="uk-form-label"><strong>CMS</strong> Database Name:</label>
                                <div class="uk-form-controls">
                                    <input name="cms_db" class="uk-input" type="text" id="cms_db" placeholder="Database (eg. yesilcms)" required>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="uk-margin-bottom uk-light">
                        <div class="uk-grid uk-grid-small" data-uk-grid>
                            <div class="uk-width-1-2@s">
                                <label class="uk-form-label"><strong>CMS</strong> Database Username:</label>
                                <div class="uk-form-controls">
                                    <input name="cms_user" class="uk-input" type="text" id="cms_user" placeholder="Username" required>
                                </div>
                            </div>
                            <div class="uk-width-1-2@s">
                                <label class="uk-form-label"><strong>CMS</strong> Database Password:</label>
                                <div class="uk-form-controls">
                                    <input name="cms_pass" class="uk-input" type="password" id="cms_pass" placeholder="Password">
                                </div>
                            </div>
                        </div>
                    </div>
                    <h2 class="uk-h5 uk-heading-divider uk-margin-small uk-text-uppercase uk-text-bold"><span><i class="fas fa-dungeon"></i> AUTH Database</span>
                        <span class="uk-align-right uk-margin-remove" id="s_auth"></span>
                    </h2>
                    <p class="uk-margin-remove-top">This database contains the general structure and data for the Account and Realm operations and usually known as <code>realmd</code></p>
                    <div class="uk-margin-top uk-margin-small-bottom uk-light">
                        <div class="uk-grid uk-grid-small" data-uk-grid>
                            <div class="uk-inline uk-width-1-2@s">
                                <label class="uk-form-label"><strong>Auth</strong> Database Hostname: <small>(also :port if exists)</small></label>
                                <div class="uk-form-controls">
                                    <input name="auth_host" class="uk-input" type="text" id="auth_host" placeholder="Hostname (eg. 127.0.0.1 or 127.0.0.1:3307)" required>
                                </div>
                            </div>
                            <div class="uk-inline uk-width-1-2@s">
                                <label class="uk-form-label"><strong>Auth</strong> Database Name:</label>
                                <div class="uk-form-controls">
                                    <input name="auth_db" class="uk-input" type="text" id="auth_db" placeholder="Database (eg. realmd)" required>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="uk-margin-bottom uk-light">
                        <div class="uk-grid uk-grid-small" data-uk-grid>
                            <div class="uk-inline uk-width-1-2@s">
                                <label class="uk-form-label"><strong>Auth</strong> Database Username:</label>
                                <div class="uk-form-controls">
                                    <input name="auth_user" class="uk-input" type="text" id="auth_user" placeholder="Username" required>
                                </div>
                            </div>
                            <div class="uk-inline uk-width-1-2@s">
                                <label class="uk-form-label"><strong>Auth</strong> Database Password:</label>
                                <div class="uk-form-controls">
                                    <input name="auth_pass" class="uk-input" type="password" id="auth_pass" placeholder="Password">
                                </div>
                            </div>
                        </div>
                    </div>
                    <h2 class="uk-h5 uk-heading-divider uk-margin-small uk-text-uppercase uk-text-bold"><span><i class="fas fa-globe"></i> WORLD Database</span>
                        <span class="uk-align-right uk-margin-remove" id="s_world"></span>
                    </h2>
                    <p class="uk-margin-remove-top">This database contains the general structure and data for the Game and usually known as <code>mangos</code> or <code>world</code></p>
                    <div class="uk-margin-top uk-margin-small-bottom uk-light">
                        <div class="uk-grid uk-grid-small" data-uk-grid>
                            <div class="uk-inline uk-width-1-2@s">
                                <label class="uk-form-label"><strong>World</strong> Database Hostname: <small>(also :port if exists)</small></label>
                                <div class="uk-form-controls">
                                    <input name="world_host" class="uk-input" type="text" id="world_host" placeholder="Hostname (eg. 127.0.0.1 or 127.0.0.1:3307)" required>
                                </div>
                            </div>
                            <div class="uk-inline uk-width-1-2@s">
                                <label class="uk-form-label"><strong>World</strong> Database Name:</label>
                                <div class="uk-form-controls">
                                    <input name="world_db" class="uk-input" type="text" id="world_db" placeholder="Database (eg. mangos)" required>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="uk-margin-small uk-light">
                        <div class="uk-grid uk-grid-small" data-uk-grid>
                            <div class="uk-inline uk-width-1-2@s">
                                <label class="uk-form-label"><strong>World</strong> Database Username:</label>
                                <div class="uk-form-controls">
                                    <input name="world_user" class="uk-input" type="text" id="world_user" placeholder="Username" required>
                                </div>
                            </div>
                            <div class="uk-inline uk-width-1-2@s">
                                <label class="uk-form-label"><strong>World</strong> Database Password:</label>
                                <div class="uk-form-controls">
                                    <input name="world_pass" class="uk-input" type="password" id="world_pass" placeholder="Password">
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="uk-margin">
                    </div>
                    <div uk-grid>
                        <div class="uk-width-1-2">
                            <button class="uk-button yesil-db-check  uk-width-1-1 uk-margin-small-bottom" type="submit" id="btn_c" form="form_checkdb"><i class="fas fa-compact-disc fa-spin"></i> Check DB Connections</button>
                        </div>
                        <div class="uk-width-1-2">
                            <?php if ($core->checkExtension() && $core->PHPVersion()): ?>
                                <button class="uk-button uk-button-primary uk-width-1-1 uk-margin-small-bottom" type="submit" id="btn_w" form="form_install" disabled><i id="i_w" class="fas fa-cog"></i> Write settings to Files</button>
                            <?php endif; ?>
                        </div>
                    </div>
                </form>
                <form id="form_checkdb" action="" method="POST" accept-charset="utf-8" autocomplete="off">
                    <input type="hidden" id="custId" name="name" value="true">
                </form>
                <div id="showresults"></div>
            </div>
            <div class="uk-width-1-4@s"></div>
        </div>
    </div>
</section>
<section class="uk-section uk-section-xsmall">
    <div class="uk-container">
        <p class="uk-text-center uk-margin-remove">This installation script is based on <span class="uk-text-bold">BlizzCMS</span> and <br/>modified by <span class="uk-text-bold"><a href="https://discord.com/users/334013264952295435" target="_blank">Yesilmen</a></span> for vMaNGOS compabilities and
            new features.
        </p>
    </div>
</section>
<div class="modal"></div>
<script>
    (function ($) {
        $.fn.replaceClass = function (pFromClass, pToClass) {
            this.removeClass(pFromClass)
            setTimeout(() => {
                this.addClass(pToClass);
            });
            return this;
        };
    }(jQuery));

    let msg_success = '<i class="fas fa-circle-check"></i> Succesfully Connected. You are good to go!';
    let msg_fail = '<i class="fas fa-circle-exclamation"></i> Failed to Connect. Please check credentials!';

    $('#form_checkdb').on('submit', e => {
        e.preventDefault();
        let dbc = $("#form_install").serializeArray();

        dbc = dbc.filter(function (elem) {
            return elem.name !== 'language' && elem.name !== 'theme' && elem.name !== 'cookie_secure';
        });

        dbc = JSON.stringify(dbc);

        $.ajax({
            type: 'post',
            data: {
                dbc
            },
            dataType: 'json',
            success: function (response) {

                if (response.CMS === true) {
                    $('#s_cms').html(msg_success);
                    $('#s_cms').replaceClass('fail notify', 'success notify');
                } else {
                    $('#s_cms').html(msg_fail);
                    $('#s_cms').replaceClass('success notify', 'fail notify');
                }

                if (response.AUTH === true) {
                    $('#s_auth').html(msg_success);
                    $('#s_auth').replaceClass('fail notify', 'success notify');
                } else {
                    $('#s_auth').html(msg_fail);
                    $('#s_auth').replaceClass('success notify', 'fail notify');
                }

                if (response.WORLD === true) {
                    $('#s_world').html(msg_success);
                    $('#s_world').replaceClass('fail notify', 'success notify');
                } else {
                    $('#s_world').html(msg_fail);
                    $('#s_world').replaceClass('success notify', 'fail notify');
                }

                if (response.CMS === true && response.AUTH === true && response.WORLD === true) {
                    $('#btn_c').attr('disabled', 'disabled');
                    $('#i_w').toggleClass('fa-spin');
                    $('#btn_w').removeAttr('disabled');
                }
            }
        });
    });

    $body = $("body");

    $(document).on({
        ajaxStart: function () {
            $body.addClass("loading");
        },
        ajaxStop: function () {
            $body.removeClass("loading");
        }
    });
</script>
</body>
</html>